export default class Ajax {
  static doAjax(options) {
    let xhr = window.XMLHttpRequest
      ? new XMLHttpRequest()
      : new ActiveXObject("Microsoft.XMLHTTP");
    if (!xhr) {
      throw new error("IE4 不支持AJAX");
    }

    options = options || {};
    let type = (options.type || "GET").toUpperCase(),
      async = options.async || true,
      url = options.url,
      data = options.data || null,
      error = options.error || function () {},
      success = options.success || function () {},
      complete = options.complete || function () {};
    //complete 不论成果失败都会执行
    if (!url) {
      throw new Error("没写URL");
    }
    //短路运算
    //  || 第一个是false 直接返回第二个参数
    //  && 第一个是true 直接返回第二个参数
    xhr.open(type, url, async);
    type === "POST" &&
      xhr.setRequsetheader(
        "Content-type",
        "application/x-www-form-urlencodeed"
      );

    //处理post数据
    function formatDatas(data) {
      let str = "";
      for (let key in data) {
        str += "&" + key + "=" + data[key];
      }
      //去掉开头多余的 &
      return str.substr(1);
    }
    xhr.send(type === "GET" ? null : formatDatas(data));
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        success(xhr.responseText);
      }
      if (xhr.status === 404) {
        error();
      }
      complete();
    };
  }
  static post(url, data, callback) {
    this.doAjax({
      type: "POST",
      url,
      data,
      success: callback,
    });
  }
  static get(url, callback) {
    this.doAjax({
      type: "GET",
      url,
      success: callback,
    });
  }
  static load(url, tagName, callback) {
    let data;
    this.get(url, (res) => {
      //禁止贪婪 .*?
      let reg = RegExp(`${tagName}.*?>(.*)(<\/${tagName})`, "s");
      data = res.match(reg)[1];
      callback(data);
    });
  }
}
